package com.aliang.shopping.util;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.contact.BasicConstant;
import com.aliang.shopping.exception.SecurityException;
import com.aliang.shopping.security.auth.Payload;

import java.util.Date;

/**
 * Jwt工具类
 */
public class JwtUtil {

    /**
     * 得到token
     */
    public static String getToken(Payload payload) {
        return JWT.create()
                //设置携带数据
                .setPayload(BasicConstant.PAYLOAD_ID, payload.getId())
                .setPayload(BasicConstant.PAYLOAD_ROLE, payload.getRole())
                //设置过期时间
                .setExpiresAt(new Date(System.currentTimeMillis() + BasicConstant.EXPIRE * 1000))
                //设置秘钥
                .setKey(BasicConstant.JWT_KEY.getBytes())
                .sign();
    }

    /**
     * 验证token
     */
    public static boolean verifyToken(String token) {
        //判断是否为空
        if (StrUtil.isBlank(token))
            return false;
        JWTValidator validator = JWTValidator.of(token);
        try {
            //验证签名
            validator.validateAlgorithm(JWTSignerUtil.hs256(BasicConstant.JWT_KEY.getBytes()));
        } catch (ValidateException e) {
            e.printStackTrace();
            throw new SecurityException(ResultCodeEnum.SIGN_INVALID);
        }
        try {
            //过期时间
            validator.validateAlgorithm(JWTSignerUtil.hs256(BasicConstant.JWT_KEY.getBytes()));
            return true;
        } catch (ValidateException e) {
            e.printStackTrace();
            throw new SecurityException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    /**
     * 根据token获取载荷信息
     *
     * @param token
     * @return
     */
    public static Payload getPayload(String token) {
        // 解析数据
        JWT jwt = JWT.of(token);
        // 获取用户id
        Long id = Long.valueOf(jwt.getPayload(BasicConstant.PAYLOAD_ID).toString());
        //获取用户角色
        Integer role = Integer.valueOf(jwt.getPayload(BasicConstant.PAYLOAD_ROLE).toString());
        // 返回载荷信息
        return new Payload(id, role);
    }
}
